require("../../assets/css/normalize.css");
require("../../assets/css/reset.css");
require("../../assets/fonts/iconfont.css");
require("./sports_course_video.less");
// 引入模块
let dom = require("../../utils/dom.js");
let axios = require("../../utils/axios.js");

document.addEventListener("DOMContentLoaded", function () {
	let startTime = Date.now();
	let duration = 0;
	// 1.点击暂停弹出模态框
	dom.get(".icon-zanting").addEventListener("click", function () {
		dom.get("#mask").style.display = "block";
		dom.get("#btnBox").style.display = "flex";
		video.pause();
		//   //计算时间
		duration += Date.now() - startTime;
	});
	// 2.点击模态框和继续按钮隐藏模态框
	dom.get("#continue").addEventListener("click", function () {
		dom.get("#mask").style.display = "none";
		dom.get("#btnBox").style.display = "none";
		video.play();
		//重新计时
		startTime = Date.now();
	});
	// 3.渲染数据到视频页面
	const fragments = JSON.parse(localStorage.getItem("fragments"));
	// console.log(fragments);
	// 渲染视频片段标题
	let num = 0; //定义一个变量控制当前播放节数
	let time = null;
	let video = dom.get("video");
	// 封装播放视频的函数
	function play() {
		dom.get("#currentPart").textContent = num + 1;
		dom.get("#totalPart").textContent = fragments.length;
		dom.get("#title").textContent = fragments[num].title;
		video.src = axios.defaults.baseURL + fragments[num].videoUrl;
		video.play();
		// 进度条
		time = setInterval(function () {
			dom.get("#progress").style.width =
				(100 * video.currentTime) / video.duration + "%";
		}, 50);
	}
	play();
	// 4.设置连续播放
	video.addEventListener("ended", function () {
		num++;
		if (num < fragments.length) {
			play();
		} else {
			num = fragments.length - 1;
		}
	});
	// 5.点击切换上一个视频
	dom.get(".icon-shangyishoushangyige").addEventListener("click", function () {
		num--;
		if (num < 0) {
			num = 0;
		}
		play();
	});
	// 6.点击切换下一个视频
	dom.get(".icon-xiayigexiayishou").addEventListener("click", function () {
		num++;
		if (num >= fragments.length) {
			num = 0;
		}
		play();
	});
	// 7.点击结束训练后回到课程训练页面
	dom.get("#end").addEventListener("click", function () {
		duration = Math.floor(duration / 1000);
		let calorie = Math.ceil(duration * 1.68);
		// console.log(calorie);
		// 发请求获取保存的数据
		axios
			.post("/api/exercise/save", {
				type: 2,
				duration,
				calorie,
			})
			.then(res => {
				if (res.data.errno === 0) {
					alert("训练已结束!!!");
					location.href = "sports_course.html";
				}
			});
	});
});
